package com.leetroll.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leetroll.api.mapper.ChapterDetailMapper;
import com.leetroll.api.service.ChapterDetailService;
import com.leetroll.api.service.FileService;
import com.leetroll.common.constant.SQLConstant;
import com.leetroll.common.entity.ChapterDetail;
import com.leetroll.common.entity.File;
import com.leetroll.common.vo.ChapterDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.leetroll.common.utils.AliyunOSSUtil.GetUrl;

@Service
public class ChapterDetailServiceImpl extends SuperServiceImpl<ChapterDetailMapper, ChapterDetail> implements ChapterDetailService {

    private final FileService fileService;

    @Autowired
    public ChapterDetailServiceImpl(FileService fileService) {
        this.fileService = fileService;
    }

    @Override
    @Cacheable(cacheNames = "listDetailByChapterId", key = "#chapterId")
    public List<ChapterDetailVO> listByChapterId(Long chapterId) {
        QueryWrapper<ChapterDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.CHAPTER_ID, chapterId);
        List<ChapterDetail> details = this.list(queryWrapper);
        List<ChapterDetailVO> vos = new ArrayList<>();
        details.forEach(detail -> {
            vos.add(fromEntity(detail));
        });
        return vos;
    }

    private ChapterDetailVO fromEntity(ChapterDetail detail) {
        ChapterDetailVO vo = new ChapterDetailVO();
        vo.setTitle(detail.getTitle());
        vo.setSeq(detail.getSeq());
        vo.setDuration(detail.getDuration());
        vo.setId(detail.getId());
        File file = fileService.getById(detail.getFileId());
        if (file != null) {
            vo.setFormat(file.getFormat());
            vo.setLink(GetUrl(file.getBucket(), file.getKey() + file.getName() + "." + file.getSuffix()));
        }
        return vo;
    }
}
